import { getAllRegion } from '@/api/region'

export function getRegionList() {
  if (sessionStorage.getItem('regionData') !== null) {
    const resList = sessionStorage.getItem('regionData')
    return JSON.parse(resList);
  } else {
    getAllRegion().then(response => {
      const { result = [] } = response
      const resList = arrayToTree(result, 'regionId', 'parentId', 'children', '1')
      sessionStorage.setItem('regionData', JSON.stringify(resList))
      return resList;
    })
  }
}

export function arrayToTree(array, id = 'id', pid = 'parentId', children = 'children', rootId){

  let data = array.slice();
  let result = [];
  let hash = {};
  data.forEach((item, index) => {
    hash[data[index][id]] = data[index]
  });
  data.forEach((item) => {
    let hashVP = hash[item[pid]]
    if (hashVP) {
      !hashVP[children] && (hashVP[children] = [])
      hashVP[children].push(item)
      result.push(hashVP);
    } else if (rootId !== undefined) {
      if (item[pid] === rootId) {
        result.push(item)
      }
    } else {
      result.push(item)
    }
  });
  return result[0].children;
};
